﻿(function(){
	
	com.yogi.core.ImageLoader = function(url) {
		com.yogi.core.ImageLoader.EVENT_IMAGELOADED = "EVENT_IMAGELOADED";		
		var m_url = url;
		var m_img = $("<img data-href=\"" + url+ "\"  />");
		m_img.load(function(){
			$(self).trigger(com.yogi.core.ImageLoader.EVENT_IMAGELOADED, {
				url: m_url,
				res:m_img
			});
		});
		var self = {
			load: function() {
				m_img.attr("src", url);
			},
			getImg: function(){
				return m_img;
			},
			getUrl:function(){
				return m_url;
			}
		};
		return self;
	};		
	com.yogi.core.JsLoader = function(url) {
		com.yogi.core.JsLoader.EVENT_JSLOADED = "EVENT_JSLOADED";		
		com.yogi.core.JsLoader.script_loader = $.getScript;
		com.yogi.core.JsLoader.PRELOAD_DIV_PREFIX = "preload_script_";
		var m_url = url;
		var guid = com.yogi.core.JsLoader.get_guid_from_url(url);
		var m_preload_div = $("<div id=\"" + com.yogi.core.JsLoader.PRELOAD_DIV_PREFIX + guid + "\" style=\"position:absolute;overflow:visible;\"></div>");
		
		function doLoad() {
			var is_hype_doc = false;
			m_preload_div.appendTo($("#DesignLayer"));		
			if(url.indexOf("_hype_generated_script.js") > 0) {
				is_hype_doc = true;				
				var preload_handler = function(e,data){
					//alert('hype script triggered.' + url + "," + data.name + "," + guid);
					if(data.name == guid && HYPE.documents[guid]) {
						var HypeDoc = HYPE.documents[guid];
						HypeDoc.url = url;
						var doc_width = HypeDoc.doc_width;
						var doc_height = HypeDoc.doc_height;
						//alert(doc_width + "," + doc_height);
						if(doc_width > 0 && doc_height > 0){
							m_preload_div.css("width",doc_width + "px");
							m_preload_div.css("height",doc_height + "px");
						}else{
							if( window.contentPanel.designSite ) {
								analyzeHypeDoc(HypeDoc,url);
							}
						}						
						//alert('begin documentLoad');
						HypeDoc.documentLoad();
						//alert('after documentLoad');
						$(window.contentPanel).unbind(com.yogi.core.ContentPanel.HYPE_DOC_LOADED_EVENT, preload_handler);
						$(self).trigger(com.yogi.core.JsLoader.EVENT_JSLOADED, {
							url: m_url,
							res:m_preload_div
						});
					}
				};
				$(window.contentPanel).bind(com.yogi.core.ContentPanel.HYPE_DOC_LOADED_EVENT, preload_handler);	
			} else {		//common js file
				var commonjs_preload_handler = function() {
					$(window.contentPanel).unbind(com.yogi.core.ContentPanel.HTML_DOC_LOADED_EVENT, commonjs_preload_handler);
					$(self).trigger(com.yogi.core.JsLoader.EVENT_JSLOADED, {
						url: m_url,
						res:m_preload_div
					});
				};
				$(window.contentPanel).bind(com.yogi.core.ContentPanel.HTML_DOC_LOADED_EVENT, commonjs_preload_handler);
			}
			com.yogi.core.JsLoader.script_loader(url, function(data,textStatus) {
				if(textStatus != "success"){
					throw "loading script:" + url + " error.";
				}
//				if(!is_hype_doc){		//not hype doc, trigger directly
//					$(self).trigger(com.yogi.core.JsLoader.EVENT_JSLOADED, {
//						url: m_url,
//						res:m_preload_div
//					});
//				}
			});
		}
		function analyzeHypeDocSize(HypeDoc){
			var scenes = HypeDoc.getScenes();			
			var doc_width = 0;
			var doc_height = 0;
			var left_alias = "a";
			var top_alias = "b";
			var width_alias = "c";
			var height_alias = "d";
			$.each(scenes, function(i_scene, scene){
				var elems = scene.initialValues;
				$.each( elems, function(i_elem, elem){
					var elem_left = parseInt(elem[left_alias]); 
					var right = elem_left + parseInt(elem[width_alias]);
					if(right > doc_width){
						doc_width = right;
					}
					var elem_top = parseInt(elem[top_alias]); 
					var bottom = elem_top + parseInt(elem[height_alias]);
					if(bottom > doc_height){
						doc_height = bottom;
					}
				});				
			});
			//Ext.dump(doc_width + "," + doc_height);
			return [doc_width, doc_height];
		}
		function analyzeHypeDocElements(HypeDoc) {
			var result = {};
			var scenes = HypeDoc.getScenes();			
			$.each(scenes, function(i_scene, scene){
				var elems = scene.initialValues;
				for(var elem_guid in elems) {
					var elem = elems[elem_guid];
					if(elem.AltID) {
						if(elem_guid * 1 == elem_guid){		//this is 1.5 version
							var guid_field = "i";
							result[elem.AltID] = elem[guid_field];
						}else{
							result[elem.AltID] = elem_guid;		//this is 1.0 version
						}
					}
				}				
			});
			return result;
		}
		function analyzeHypeDoc(HypeDoc,url) {
			var doc_size = analyzeHypeDocSize(HypeDoc);
			var doc_width = doc_size[0];
			var doc_height = doc_size[1];
			m_preload_div.css("width",doc_width + "px");
			m_preload_div.css("height",doc_height + "px");			
			var elements_map_id_guid = analyzeHypeDocElements(HypeDoc);				
			HypeDoc.elements_map = elements_map_id_guid;		//record realtime information
			var rm = new com.yogi.core.net.YogiSmileRemoteMethod("AppCatalogSupport");
			rm.callMethod("SaveHypeSceneSize", [url,doc_width,doc_height, Ext.encode(elements_map_id_guid) ]);
		}
		var self = {
			load: function() {
				doLoad();
			},
			getDIV: function(){
				return m_preload_div;
			},
			getUrl:function(){
				return m_url;
			}
		};
		return self;
	};
	com.yogi.core.JsLoader.get_guid_from_url = function(_url){
		var upFileBase = "/upfiles";
        var pGuid = _url.toLowerCase().indexOf(upFileBase);
        var pSlash = pGuid + upFileBase.length + 1;
        var qGuid = _url.indexOf("/", pSlash);
        var guid = _url.substr(pSlash, qGuid - pSlash);
        return guid;
	};
	com.yogi.core.ResourceLoader = function(resUrls ){
		com.yogi.core.ResourceLoader.image_suffixs = [".txt",".gif",".jpg",".jpeg",".bmp",".png"]; 
		com.yogi.core.ResourceLoader.EVENT_RESLOADED = "EVENT_RESLOADED";
		
		var m_key = { };
		var m_resUrls = resUrls;
		/**
		 * 资源地图，key是url，value就是资源句柄，比如 "resources/1.jpg" --> Image对象 
		 */		
		var m_resMap = {};
		var m_count = resUrls.length;
		var m_loadedCount = 0;
		
		function onResourceLoaded(e, data) {
			var url = data.url;
			m_loadedCount++;
			var cache = m_resMap[url];
			if(Ext.isEmpty(cache)){
				m_resMap[url] = data.res;
			}
			if(	m_loadedCount == m_count) {					
//				for(var sUrl in m_resMap){
//					Ext.dump("ResourceLoader:" + sUrl + "=" + m_resMap[sUrl].get());
//				}
				$(self).trigger(com.yogi.core.ResourceLoader.EVENT_RESLOADED, {
					resources:m_resMap,
					context:m_key
				});
			}
		}		
		function doLoad() {
			$.each(m_resUrls, function(i, url){				
				var p = url.lastIndexOf(".");
				var suffix = url.substr(p).toLowerCase();
				//alert(url + ".suffix=" + suffix);
				if(com.yogi.core.ResourceLoader.image_suffixs.indexOf(suffix) >= 0) {
					var imgLoader = new com.yogi.core.ImageLoader(url);
					$(imgLoader).bind(com.yogi.core.ImageLoader.EVENT_IMAGELOADED, onResourceLoaded);					
					//m_resMap[url] = imgLoader;	
					imgLoader.load();
				}else if(".js" == suffix){
					var jsLoader = new com.yogi.core.JsLoader(url);
					$(jsLoader).bind(com.yogi.core.JsLoader.EVENT_JSLOADED, onResourceLoaded);
					jsLoader.load();
				}
			});
		}
		var self = {
			load: function() {
				doLoad();
			},
			setKey: function(k) {
				m_key = k;
			},
			getKey: function() {
				return m_key;
			}
		};
		return self;
	};
	com.yogi.core.ResourceBundle = new ( function() {
		/**
		 * 缓存的资源地图，key是url，value就是资源句柄，比如 "resources/1.jpg" --> Image对象 
		 */	
		var m_resMap = new Array();		
		/**
		 * 各个资源的处理函数句柄，key是url，value是函数，函数参数就是资源对象 
		 */		
		var m_resFunc = new Array();
		
		var resource_loader_class = com.yogi.core.ResourceLoader;
		
		function onResLoaded(e, data){
			var resources = data.resources;			
			for(var key in resources){
				var res = resources[key];
				if(m_resMap[key] == null){
					m_resMap[key] = res;			//cache it
				}
				var callBack = m_resFunc[key];
				if(callBack != null){
					callBack(res);
				}
			}			
		}
		function onResArrayLoaded(e, data) {
			var resources = data.resources;
			for(var key in resources){
				var res = resources[key];
				//alert("ResourceBundle:" + key + "=" + res.get());
				if(m_resMap[key] == null){
					m_resMap[key] = res;			//cache it
				}				
			}
			var ctx = data.context;
			if(ctx != null && ctx.length == 3)
			{				
				(ctx[0]).call(ctx[2],ctx[1]);		//callback
			}
		}
		function doLoadResources(resUrls,callBack,scope) {
			var resUrlsToLoad = new Array();
			var resLoaded = new Array();
			$.each( resUrls, function(i, url) {				
				var res = m_resMap[url];
				if(res == null) {
					resUrlsToLoad.push(url);
				} else {
					resLoaded[url] = res;
				}
			});
			if(resUrlsToLoad.length > 0)	{
				//console.log("resUrlsToLoad:");
				//console.log(resUrlsToLoad);
				var loader = new resource_loader_class(resUrlsToLoad);
				loader.setKey( [callBack,resUrls,scope || self] );
				$(loader).bind(com.yogi.core.ResourceLoader.EVENT_RESLOADED, onResArrayLoaded);
				loader.load();
			} else {
				callBack(resUrls);
			}
		}
		var self = {
			getInstance: function() {
				return this;
			},
			loadResources: function(resUrls,callBack,scope) {
				doLoadResources(resUrls,callBack,scope);
			},
			/**
			 * 获取资源 
			 * @param resUrl 资源url
			 * @param callBack 回调,函数签名如:  processRes(res); 参数是资源本身
			 */		
			getResource: function (resUrl,callBack) {
				//先检查缓存，如果有，直接返回
				var cacheObj = m_resMap[resUrl];				
				if(cacheObj != null) {
					callBack(cacheObj);
				}
				
				var loader = new com.yogi.core.ResourceLoader([resUrl]);
				m_resFunc[resUrl] = callBack;
				$(loader).bind(com.yogi.core.ResourceLoader.EVENT_RESLOAED, onResLoaded);
				loader.load();
			},
			/**
			 * 在确保已经加载好的情况下直接获取资源 
			 * @param resUrl 资源url		 
			 */
			getResourceDirect: function(resUrl) {
				var cacheObj = m_resMap[resUrl];
				//Ext.dump("getResourceDirect:" + resUrl + "=" + cacheObj.get());
				return (cacheObj);
			}
		};
		return self;
	})();
	function dummy(){
		new com.yogi.core.ResourceBundle();
	}
	$(window).trigger(com.yogi.core.EVENT_EXTERNAL_SCRIPT_LOADED,  { script:"com.yogi.core.ResourceBundle" });
})();